<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Petr
 * Date: 30.12.10
 * Time: 22:42
 * To change this template use File | Settings | File Templates.
 */
namespace Albireo\Application;

use Nette\Object;
use Albireo\Application\ApplicationManager;
use \InvalidArgumentException;
use Albireo\Application\ApplicationNotFoundException;

//TODO: first version of executing applications, later we have to deal with security and other methods of connection
class ApplicationExecutor extends Object {
    private $user;

    public function __construct($user) {
        if ($user->getIdentity() == NULL) {
            throw new InvalidArgumentException("You must be signed in to execute apps");
        }
        $this->user = $user;
    }

    public function execute($name, $args = null, $flags = null, $settings = null) {
        $control = new ApplicationManager($this->user);
        $app = $control->getApplicationByName($name);
        //TODO: now only get is possible later we will add post and also ssl
        //TODO: add Proxy
        //TODO: add base when needed (on return?)
        //TODO: create token associated with a current user in relation user-app-token to make API authentication possible
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $app->getUrl());
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        if ($output === false ) {
            $message = curl_error($ch);
            curl_close($ch);
            throw new ApplicationNotFoundException($message);
        }

        curl_close($ch);
        return $output;
    }
}